package com.lambert.ginkgo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lambert.ginkgo.WebClientTemplate;
import com.lambert.ginkgo.config.OpenAIProperties;
import com.lambert.ginkgo.dto.OpenAIRequest;
import com.lambert.ginkgo.dto.OpenAIResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Collections;

/**
 * OpenAI服务类：使用WebClientTemplate调用接口
 */
@Slf4j
@Service
public class OpenAIService {

    // 注入OpenAI专用的WebClientTemplate
    private final WebClientTemplate webClientTemplate;
    private final OpenAIProperties properties;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public OpenAIService(
            @Qualifier("openaiWebClientTemplate") WebClientTemplate webClientTemplate,
            OpenAIProperties properties) {
        this.webClientTemplate = webClientTemplate;
        this.properties = properties;
    }

    /**
     * 非流式调用：一次性获取完整响应
     */
    public Mono<String> chat(String userMessage) {
        // 构建OpenAI请求参数
        OpenAIRequest request = new OpenAIRequest();
        request.setModel(properties.getDefaultModel());
        request.setMessages(Collections.singletonList(
                new OpenAIRequest.Message("user", userMessage)
        ));
        request.setTemperature(0.7);
        request.setMaxTokens(1024);

        // 调用OpenAI的聊天接口
        return webClientTemplate.post(
                "/chat/completions",  // 请求路径
                request,               // 请求体
                OpenAIResponse.class   // 响应类型
        ).mapNotNull(response -> {
            // 提取回复内容
            if (response.choices() != null && !response.choices().isEmpty()) {
                return response.choices().get(0).message().content();
            }
            return "未获取到有效回复";
        });
    }

    /**
     * 流式调用：实时获取响应片段（SSE）
     */
    public Flux<String> streamChat(String userMessage) {
        OpenAIRequest request = new OpenAIRequest();
        request.setModel(properties.getDefaultModel());
        request.setMessages(Collections.singletonList(
                new OpenAIRequest.Message("user", userMessage)
        ));
        request.setStream(true); // 启用流式返回
        Mono<OpenAIRequest> requestFlux = Mono.just(request);

        // 调用接口并处理流式响应（假设WebClientTemplate有postFlux方法）
        return webClientTemplate.postFlux(
                        "/chat/completions",
                        requestFlux,
                        OpenAIRequest.class,
                        String.class , // 流式响应为字符串片段
                        HttpHeaders.EMPTY
                )
                // 解析SSE格式（data: {json}）
                .map(line -> {
                    log.info("原始响应：{}", line);
                    return line.replace("data: ", "");
                })
                .filter(line -> !line.isEmpty() && !"[DONE]".equals(line))
                // 提取内容片段
                .map(json -> json);
    }
}